#include "client.h"

#include <string.h>
#include <stdlib.h>
#include "log.h"

inline struct client * get_client(struct rb_root * root,int fd)
{
	struct rb_node * n = root->rb_node;

	while (n) {
            struct client *data = container_of(n, struct client, node);
            int result;

            result = fd - data->fd;

	    if (result < 0) {
                n = n->rb_left;
            } else if (result > 0) {
                n = n->rb_right;
            } else {
                return data;
            }
        }
        return NULL;
}

inline int rb_insert_client(struct rb_root *root, struct client *data)
{
    

    struct rb_node **new = &(root->rb_node);
    struct rb_node *parent = NULL;

    /* Figure out where to put new node */
    while (*new) {
        struct client *this = container_of(*new, struct client, node);
        int result = data->fd - this->fd;

        parent = *new;
        if (result < 0) {
            new = &((*new)->rb_left);
        } else if (result > 0) {
            new = &((*new)->rb_right);
        } else { 
            return 0;
        }
    }

    /* Add new node and rebalance tree. */
    rb_link_node(&data->node, parent, new);
    rb_insert_color(&data->node, root);

    return 1;
}
inline struct client *add_client(struct rb_root *root,int fd)
{
    struct client *new_client = malloc(sizeof(struct client));
    new_client->fd = fd;
    new_client->idx = 0;
    if(rb_insert_client(root,new_client)) {
        return new_client;
    } else {
        //Log(3,"Duplicate fd: %i",fd);
        free(new_client);
        return 0;
    }
}

inline void del_client(struct rb_root *root,struct client* cl)
{
    rb_erase(&cl->node,root);
    free(cl);
}

void test_clients(int add)
{
    Log_msg(3,"Begin clients testing");
    struct rb_root clients = RB_ROOT;
    const int runs = add;
    int i,add_count = 0;
    Log(3,"Adding %i elements",runs);
    for (i = 0; i < runs; i++) {
        if(!add_client(&clients, rand() % runs)) {
            //Log_msg(2,"Client adding failed");
        } else {
            ++add_count;
        }
    }

    Log(3,"Added elements: %i",add_count);

    int found = 0;

    for (i = 0; i < runs; i++) {
        struct client* cl = get_client(&clients, i);
        if (cl) {
            //Log(2, "%d", cl->fd);
            ++found;
        }
    }
    Log(3,"Found elements: %i",found);


    int deleted = 0;
    Log(3,"Deleting elements");
    for (i = 0; i < runs; i++) {
        struct client* cl = get_client(&clients, i);
        if (cl) {
            ++deleted;
            del_client(&clients,cl);
        }
    }

    Log(3,"Deleted: %i",deleted);

    Log_msg(3,"End clients testing");
}
